#include "datacollector.h"

///
/// @param  dir     Reference to the data directory
/// @param  parent  Pointer to the parent object
/// Initialize the data collector
DataCollector::DataCollector(const QDir &dir, QObject *parent) :
    QThread(parent),
    iterator_(dir, QDirIterator::Subdirectories),
    stopped_(false)
{}

///
/// Starts the scanning
void DataCollector::run()
{
    while (iterator_.hasNext()) {
        QString entry(iterator_.next());
        if (QFileInfo(entry).suffix().toLower() == "avi") {
            QString fileName(QFileInfo(entry).fileName());
            QString title;
            int year;
            QRegExp rx("^(.+)-(.+).avi$");
            if (rx.indexIn(fileName) != -1) {
                title = rx.cap(1).trimmed();
                year = rx.cap(2).toInt();
            }
            Movie *movie = new Movie;
            movie->setTitle(title);
            movie->setFilePath(entry);
            movie->setYear(year);
            if (movie->saveToDatabase()) {
                QSharedPointer<Movie> pMovie(movie);
                movieList_.push_back(pMovie);
            } else
                delete movie;

            // emit fileCountChanged(fileList_.count());
        }
    }
}

///
/// An event to stop the scanning process
void DataCollector::stop()
{
    stopped_ = true;
}

///
/// @return     A const reference to file list
///
/// Returns a const reference to the file list result from scanning
const MovieList &DataCollector::getFileList() const
{
    return movieList_;
}
